package org.jeecg.modules.htxincailiao.support.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.SmartBeanUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.constant.HTAccountTypeEnum;
import org.jeecg.modules.htxincailiao.account.domain.bo.HTAccountAddBO;
import org.jeecg.modules.htxincailiao.account.entity.HTMerchant;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.im.domain.bo.IMUserAddBO;
import org.jeecg.modules.htxincailiao.im.entity.IMUser;
import org.jeecg.modules.htxincailiao.im.service.IIMUserService;
import org.jeecg.modules.htxincailiao.shop.entity.HTShop;
import org.jeecg.modules.htxincailiao.shop.service.IHTShopService;
import org.jeecg.modules.htxincailiao.support.entity.HTCustomerSupport;
import org.jeecg.modules.htxincailiao.support.service.IHTCustomerSupportService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ht_customer_support
 * @Author: jeecg-boot
 * @Date: 2023-03-18 14:14:57
 * @Version: V1.0
 */
@Api(tags = "ht_customer_support")
@RestController
@RequestMapping("/support/hTCustomerSupport")
@Slf4j
public class HTCustomerSupportController extends JeecgController<HTCustomerSupport, IHTCustomerSupportService> {
    @Autowired
    private IHTCustomerSupportService hTCustomerSupportService;

    @Resource
    private IHTShopService shopService;

    @Resource
    private IHTAccountService accountService;

    @Resource
    private IIMUserService iimUserService;

    @Resource
    ISysUserService sysUserService;


    /**
     * 获取官方客服的信息
     *
     * @return
     */
    @AutoLog(value = "ht_customer_support-编辑")
    @ApiOperation(value = "ht_customer_support-编辑", notes = "ht_customer_support-编辑")
    @GetMapping(value = "/getShopSupportInfo")
    public Result<?> getShopSupportInfo(HTCustomerSupport hTCustomerSupport) {
        if (oConvertUtils.isEmpty(hTCustomerSupport.getShopId())) {
            return Result.error("店铺ID不能为空");
        }
        HTCustomerSupport support = hTCustomerSupportService.queryByShopId(hTCustomerSupport.getShopId());
        if (oConvertUtils.isEmpty(support)) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(support);
    }

    /**
     * 获取官方客服的信息
     *
     * @return
     */
    @AutoLog(value = "ht_customer_support-编辑")
    @ApiOperation(value = "ht_customer_support-编辑", notes = "ht_customer_support-编辑")
    @GetMapping(value = "/getPlatformSupportInfo")
    public Result<?> getPlatformSupportInfo() {
//        SysUser admin = sysUserService.getUserByName("admin");
        //1638110348433375233
        String supportId = "1638110348433375233";
//        HTCustomerSupport support = hTCustomerSupportService.getById("1638110348433375233");
        HTCustomerSupport support = hTCustomerSupportService.getById(supportId);
        if (oConvertUtils.isEmpty(support)) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(support);
    }


    /**
     * 分页列表查询
     *
     * @param hTCustomerSupport
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_customer_support-分页列表查询")
    @ApiOperation(value = "ht_customer_support-分页列表查询", notes = "ht_customer_support-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTCustomerSupport hTCustomerSupport,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTCustomerSupport> queryWrapper = QueryGenerator.initQueryWrapper(hTCustomerSupport, req.getParameterMap());
        Page<HTCustomerSupport> page = new Page<HTCustomerSupport>(pageNo, pageSize);
        IPage<HTCustomerSupport> pageList = hTCustomerSupportService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hTCustomerSupport
     * @return
     */
    @AutoLog(value = "ht_customer_support-添加")
    @ApiOperation(value = "ht_customer_support-添加", notes = "ht_customer_support-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HTCustomerSupport hTCustomerSupport) {

        // 根据shopID获取店铺信息，对sys_user_id im_user_Id
        HTShop shop = null;
        if (oConvertUtils.isEmpty(hTCustomerSupport.getShopId())) {
            return Result.error("店铺ID不能为空");
        }
        shop = shopService.getById(hTCustomerSupport.getShopId());
        if (oConvertUtils.isEmpty(shop)) {
            return Result.error("店铺不存在");
        }

        // 店铺的后天账户ID为空就创建一个
        HTPlatformUser platformUser = null;
        HTAccountAddBO bo = null;
        SysUser sysUser = null;

        if (oConvertUtils.isEmpty(shop.getSellerId())) {
            return Result.error("店主不存在");
        }
        platformUser = accountService.queryUserById(shop.getSellerId());
        if (oConvertUtils.isEmpty(platformUser)) {
            return Result.error("店主查询失败");
        }

        if (oConvertUtils.isEmpty(shop.getSysUserId())) {
            bo = new HTAccountAddBO();
            BeanUtils.copyProperties(platformUser, bo);
            bo.setAccountType(HTAccountTypeEnum.values()[platformUser.getAccountType()]);

            //创建后台账户
            try {
                sysUser = accountService.handleSysUserForSignUp(bo);
            } catch (Exception e) {
                return Result.error("创建后台账户出错");
            }
        } else {
            sysUser = sysUserService.getUserById(shop.getSysUserId());
        }

        shop.setSysUserId(sysUser.getId());
        shopService.updateById(shop);

        hTCustomerSupport.setSysUserId(sysUser.getId());

        IMUser imUser = iimUserService.queryByUserId(sysUser.getId());
        //没有对应的IM用户就创建一个
        if (oConvertUtils.isEmpty(imUser)) {
            IMUserAddBO imUserAddBO = new IMUserAddBO();
            BeanUtils.copyProperties(platformUser, imUserAddBO);
            imUserAddBO.setUserId(sysUser.getId());
            boolean succeed = accountService.handleSignUpForImUser(imUserAddBO);
            if (!succeed) {
                return Result.error("创建IM用户出错");
            }
        }

        imUser = iimUserService.queryByUserId(sysUser.getId());
        if (oConvertUtils.isEmpty(imUser)) {
            return Result.error("查询IM用户出错");
        }

        hTCustomerSupport.setImUserId(imUser.getId());
        hTCustomerSupport.setType(platformUser.getAccountType());

        hTCustomerSupportService.save(hTCustomerSupport);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hTCustomerSupport
     * @return
     */
    @AutoLog(value = "ht_customer_support-编辑")
    @ApiOperation(value = "ht_customer_support-编辑", notes = "ht_customer_support-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HTCustomerSupport hTCustomerSupport) {
        hTCustomerSupportService.updateById(hTCustomerSupport);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_customer_support-通过id删除")
    @ApiOperation(value = "ht_customer_support-通过id删除", notes = "ht_customer_support-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hTCustomerSupportService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_customer_support-批量删除")
    @ApiOperation(value = "ht_customer_support-批量删除", notes = "ht_customer_support-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hTCustomerSupportService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_customer_support-通过id查询")
    @ApiOperation(value = "ht_customer_support-通过id查询", notes = "ht_customer_support-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HTCustomerSupport hTCustomerSupport = hTCustomerSupportService.getById(id);
        if (hTCustomerSupport == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTCustomerSupport);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hTCustomerSupport
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTCustomerSupport hTCustomerSupport) {
        return super.exportXls(request, hTCustomerSupport, HTCustomerSupport.class, "ht_customer_support");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTCustomerSupport.class);
    }

}
